<template>
  <div class="page-container" ref="pageContainer">
    <!-- 循环渲染每个月份的签到区域 -->
    <div v-if="allMonthsData.length === 0" style="color: #999;">数据加载中...</div>

    <div class="daily-sign" v-for="(monthData, index) in allMonthsData" :key="monthData.month"
      :ref="`monthContainer${index}`" :style="{ marginBottom: monthData.items.length > 0 ? '4vh' : '0' }">
      <div class="month" v-if="monthData.items.length > 0">{{ formatMonthDisplay(monthData.month) }}</div>

      <!-- 数据加载完成后显示签到项 -->
      <div class="sign-card-box" v-if="monthData.items.length > 0">
        <div class="sign-item" v-for="item in monthData.items" :key="item.id" @click="handleSignItemClick(item.date)">
          <div class="sign-img">
            <img :src="item.cover" alt="">
          </div>
          <div class="sign-time">{{ item.date }}</div>
        </div>
      </div>

      <div v-if="monthData.loading" class="loading">加载中...</div>
    </div>


    <div v-if="isLoading" class="bottom-loading">加载中...</div>

    <div class="card-details" :class="{ 'visible': isDetailsVisible, 'exiting': isExiting }"
      @transitionend="handleTransitionEnd">
      <div class=" card-details-header">
        <van-icon name="arrow-left" class="close-details" @click="handleCloseDetails" />
        <div class="card-details-time">{{ selectedDate }}</div>
        <i class="one-icon one-icon-share"></i>
      </div>

      <div class="part-one" v-if="detailsData.length !== 0">
        <div class="daily-details">
          <div class="details-img">
            <img :src="detailsData.img_url" alt="">
          </div>
          <div class="photographer">摄影 | {{ detailsData.pic_info }}</div>
          <div class="details-text" v-html="detailsData.forward.replace(/\r\n/g, '<br>')"></div>
          <div class="details-text-author">{{ detailsData.words_info }}</div>
        </div>
        <div class="re-bottom">
          <div class="left">
            <i class="recommend-iconfont icon-xiaoji"></i>
            <span>小记</span>
          </div>
          <div class="right">
            <i class="one-icon one-icon-note"></i>
            <i class="recommend-iconfont icon-favorites favorites"></i>
            <div class="like">
              <i class="one-icon" :class="detailsData.isLiked ? 'one-icon-liked' : 'one-icon-like'"
                @click="toggleLike(detailsData)"></i>
              <span>{{ detailsData.like_count }}</span>
            </div>
            <i class="recommend-iconfont icon-share"></i>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getDailySignListByMonth, getDailySignByDate } from '@/api/api'
import { Icon } from 'vant'

export default {
  components: {
    [Icon.name]: Icon
  },
  data() {
    return {
      allMonthsData: [], // 存储所有月份的数据
      currentMonth: '', // 当前月份，格式：YYYY-MM
      isLoading: false, // 是否正在加载中
      loadLock: false, // 防止重复加载的锁
      isLastPage: false, // 是否已经加载到最前的月份
      selectedDate: '', // 记录用户点击的日期
      detailsData: [], // 存储请求到的详情数据
      isDetailsVisible: false, // 控制详情页显示/隐藏
      scrollPosition: 0, // 存储滚动位置
      isExiting: false,// 退出状态管理
    }
  },
  methods: {
    // 获取当前月份
    getCurrentMonth() {
      const date = new Date()
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      return `${year}-${month.toString().padStart(2, '0')}`
    },

    // 获取上一个月
    getPreviousMonth(monthStr) {
      const [year, month] = monthStr.split('-').map(Number)
      let prevYear = year
      let prevMonth = month - 1

      if (prevMonth < 1) {
        prevMonth = 12
        prevYear -= 1
      }

      return `${prevYear}-${prevMonth.toString().padStart(2, '0')}`
    },

    // 格式化月份显示
    formatMonthDisplay(monthStr) {
      const month = monthStr.split('-')[1]
      return `${month}月`
    },

    // 加载指定月份的数据
    loadMonthData(monthStr) {
      // 检查该月份是否已加载
      if (this.allMonthsData.some(item => item.month === monthStr)) {
        return
      }

      // 添加加载状态的月份数据
      this.allMonthsData.push({
        month: monthStr,
        items: [],
        loading: true
      })

      // 排序月份，确保最新的月份在前面
      this.allMonthsData.sort((a, b) => b.month.localeCompare(a.month))

      // 请求数据
      getDailySignListByMonth(monthStr)
        .then(res => {
          // 确保数据是数组
          const items = Array.isArray(res.data) ? res.data : []

          // 更新数据
          const index = this.allMonthsData.findIndex(item => item.month === monthStr)
          if (index !== -1) {
            this.$set(this.allMonthsData, index, {
              month: monthStr,
              items: items,
              loading: false
            })
          }
        })
        .catch(error => {
          console.error(`加载${monthStr}数据失败:`, error)
          // 加载失败也更新状态
          const index = this.allMonthsData.findIndex(item => item.month === monthStr)
          if (index !== -1) {
            this.$set(this.allMonthsData[index], 'loading', false)
          }
        })
    },

    // 加载更多月份数据
    loadMoreMonths() {
      // 如果正在加载中、已加锁或已是最后一页，不执行
      if (this.isLoading || this.loadLock || this.isLastPage) return

      this.loadLock = true // 加锁防止重复请求
      this.isLoading = true // 显示加载状态
      console.log('开始加载更多月份数据')

      // 获取最早的月份
      if (this.allMonthsData.length === 0) {
        // 如果没有数据，加载当前月份
        this.loadMonthData(this.currentMonth)
        this.isLoading = false
        this.loadLock = false
        return
      }

      // 按月份排序，找出最早的月份
      const sortedMonths = [...this.allMonthsData].sort((a, b) =>
        a.month.localeCompare(b.month)
      )
      const earliestMonth = sortedMonths[0].month

      // 获取上一个月
      const prevMonth = this.getPreviousMonth(earliestMonth)
      console.log(prevMonth)

      // 检查是否已经到达2016年1月
      if (prevMonth < '2016-01') {
        this.isLastPage = true
        this.isLoading = false
        this.loadLock = false
        console.log('已经到达最早月份')
        return
      }

      // 加载前一个月的数据
      this.loadMonthData(prevMonth)

      // 完成后更新状态
      this.isLoading = false
      this.loadLock = false
    },

    // 检查是否滚动到页面底部
    checkScrollBottom() {
      // 如果详情页显示，不执行
      if (this.isDetailsVisible) return;

      // 如果正在加载中、已加锁或已是最后一页，不执行
      if (this.isLoading || this.loadLock || this.isLastPage) return

      const container = this.$refs.pageContainer
      if (!container) return

      // 计算最后一个月份容器的位置
      const lastMonthIndex = this.allMonthsData.length - 1
      const lastMonthContainer = this.$refs[`monthContainer${lastMonthIndex}`]?.[0]

      if (!lastMonthContainer) return

      // 计算最后一个月份容器的底部位置
      const lastMonthBottom = lastMonthContainer.offsetTop + lastMonthContainer.offsetHeight
      // 容器的滚动高度和可视高度
      const clientHeight = container.clientHeight
      const scrollTop = container.scrollTop

      // 当滚动到距离底部200px以内时，加载下一个月份
      if (lastMonthBottom - scrollTop <= clientHeight + 200) {
        this.loadMoreMonths()
      }
    },

    // 获取用户点击的卡片的详情数据
    handleSignItemClick(date) {
      // 记录滚动位置
      this.scrollPosition = this.$refs.pageContainer.scrollTop;
      // 记录点击的日期
      this.selectedDate = date;

      // 移除滚动监听，防止详情页显示时触发加载
      if (this.$refs.pageContainer) {
        this.$refs.pageContainer.removeEventListener('scroll', this.checkScrollBottom);
      }
      getDailySignByDate(this.selectedDate)
        .then(res => {
          this.detailsData = res.data;
          this.isDetailsVisible = true;
        })
        .catch(error => {
          console.error(`加载${this.selectedDate}的详情数据失败:`, error);
          this.detailsData = [];
        });

      this.isDetailsVisible = true;
      this.isExiting = false
    },

    // 关闭详情页
    handleCloseDetails() {
      this.isExiting = true;
    },

    // 过渡动画结束处理
    handleTransitionEnd() {
      if (this.isExiting) {
        // 动画结束后重置状态
        this.isDetailsVisible = false;
        this.isExiting = false;
        this.detailsData = [];

        // 恢复滚动监听和位置
        if (this.$refs.pageContainer) {
          this.$refs.pageContainer.addEventListener('scroll', this.checkScrollBottom);
          this.$refs.pageContainer.scrollTop = this.scrollPosition;
        }
      }
    },

    toggleLike(item) {
      if (item.isLiked) {
        item.like_count--;
      } else {
        item.like_count++;
      }
      item.isLiked = !item.isLiked;
    },

    // 检查路由 query 参数，如果存在 date，则自动打开详情
    checkRouteQuery() {
      const date = this.$route.query.date;
      if (date) {
        // 直接调用 handleSignItemClick 打开详情
        this.handleSignItemClick(date);
        // 清除路由中的 query 参数，避免刷新页面时重复打开
        this.$router.replace({ query: {} });
      }
    }
  },
  created() {
    // 获取当前月份
    this.currentMonth = this.getCurrentMonth()

    // 初始加载当前月和上一个月的数据
    this.loadMonthData(this.currentMonth)
    const prevMonth1 = this.getPreviousMonth(this.currentMonth)
    this.loadMonthData(prevMonth1)
  },
  mounted() {
    // 监听滚动事件，使用自定义容器的滚动事件而非window
    this.$refs.pageContainer.addEventListener('scroll', this.checkScrollBottom)
    // 检查路由参数，如果存在 date，则自动打开详情
    this.checkRouteQuery()
  },
  beforeDestroy() {
    // 移除滚动事件监听
    this.$refs.pageContainer.removeEventListener('scroll', this.checkScrollBottom)
  }
}
</script>

<style scoped lang="less">
.page-container {
  padding: 10vh 10px 0;
  background-color: #fff;
  height: 100vh;
  box-sizing: border-box;
  overflow-y: auto;
}

.sign-card-box {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 3vh;
  margin-bottom: 5vh;
}

.daily-sign {
  margin-bottom: 4vh;

  .month {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    color: #666;
    margin-bottom: 2vh;
    padding: 5px 0;

    &::before,
    &::after {
      content: '';
      width: 40%;
      height: 1px;
      transform: scaleY(0.2);
      background-color: #b9b9b9;
    }

    &::before {
      margin-right: 10px;
    }

    &::after {
      margin-left: 10px;
    }
  }

  .loading {
    text-align: center;
    padding: 10vh 0;
    color: #999;
    font-size: 14px;
  }

  .sign-item {
    height: 25vh;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .sign-img {
      height: 80%;
      overflow: hidden;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-top-left-radius: 4px;
        border-top-right-radius: 4px;
      }
    }

    .sign-time {
      height: 20%;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 14px;
      color: #666;
      background-color: #f9f9f9;
      border-bottom-left-radius: 4px;
      border-bottom-right-radius: 4px;
    }
  }
}

.bottom-loading {
  text-align: center;
  padding: 3vh 0;
  color: #999;
  font-size: 14px;
}

.card-details {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: #fff;
  z-index: 10;
  transform: translateY(100%);
  opacity: 0;
  transition: transform 0.3s ease;
  overflow: hidden;

  &.visible {
    transform: translateY(0);
    opacity: 1;
  }

  &.exiting {
    transform: translateX(100%);
    opacity: 0;
  }

  .card-details-header {
    height: 5vh;
    width: 100vw;
    border-bottom: 1px solid #ececec;
    padding: 0 3vw;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 3vh;

    .close-details {
      color: #ccc;
      font-size: 14px;
      cursor: pointer;
    }

    .card-details-time {
      font-size: 12px;
      font-weight: 300;
    }

    .one-icon {
      font-size: 14px;
      color: #ccc;
    }
  }

  .part-one {
    width: 100%;
    padding: 0 15px 10px;
    box-sizing: border-box;
    background-color: #fff;
    margin-bottom: 8px;

    .daily-details {
      width: 100%;
      min-height: 50vh;
      border-radius: 8px;
      position: relative;
      box-shadow: 0 3px 3px rgba(0, 0, 0, 0.164);

      .details-img {
        width: 100%;

        img {
          width: 100%;
          border-top-left-radius: 8px;
          border-top-right-radius: 8px;
        }
      }

      .photographer {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 8px;
        color: #dadada;
        padding: 10px 0;
        margin-bottom: 20px;
      }

      .details-text {
        line-height: 1.8;
        font-size: 12px;
        padding: 0 3vw;
        margin-bottom: 10vh;
      }

      .details-text-author {
        padding-bottom: 20px;
        font-size: 8px;
        color: #dadada;
        display: flex;
        justify-content: center;
      }
    }

    .re-bottom {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 10px;
      padding: 15px 0;
      box-sizing: border-box;

      .left {
        display: flex;
        align-items: center;
        cursor: pointer;
        margin-left: 5px;

        span {
          font-size: 10px;
          color: #cdcdcd;
        }

        i {
          margin-right: 3px;
        }
      }

      .right {
        width: 40vw;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-right: 5px;

        .favorites {
          margin-left: -10px;
        }

        .like {
          display: flex;
          align-items: center;
          cursor: pointer;
          margin: -15px;
          color: #cdcdcd;

          i {
            margin-right: 3px;
          }
        }
      }
    }
  }
}
</style>
